<template>
  <div class="fileContent">
    <label>
      <slot></slot>
      <input
        ref="inputFile"
        class="fileClass"
        @change="handleReadFile"
        v-bind="$props"
        type="file"
        :accept="accept"
      />
    </label>
  </div>
</template>
<script>
export default {
  props: {
    autoComplete: {
      type: String,
      default: 'off',
    },
    multiple: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    accept: { type: [String, Array], default: () => ['image/*'] },
    maxSize: { type: Number, default: 999 },
    name: { type: String, default: '' },
    index: { type: Number, default: 0 },
	  limit: { type: Number, default: 1 },
  },
  methods: {
    async handleReadFile(e) {
      let files = e.target.files || e.dataTransfer.files
      let newFiles = [] 
      for (const file of files) if (file.size / 1024 / 1024 < this.maxSize) newFiles.push(file)
      if (files.length > this.limit) return this.$emit('handleReadFile', { message: `单次上传文件数量限制为${this.limit}个, 您这次选择了${files.length}个文件`})
      if (files.length != newFiles.length) return this.$emit('handleReadFile', { message: `部分文件大小超过${this.maxSize}M, 请重新选择`})
      await new Promise(async (resolve, reject) => {
        let fileInfoList = []
        for (let i of files) {
          let reader = new FileReader()
          await reader.readAsDataURL(i)
          reader.onload = e => {
            fileInfoList.push({
              file: i,
              size: i.size,
              result: e.target.result,
              local: URL.createObjectURL(i),
              event: e,
            })
            if (fileInfoList.length == files.length) {
              resolve()
              this.$emit('handleReadFile', {
                ...this.$props,
                files,
                fileInfoList,
                message: ''
              })
              this.$refs.inputFile.value = ''
            }
          }
          reader.onerror = e => {
            this.$emit('handleReadFile', {message: '文件读取失败'})
            reject()
          }
        }
      })
    },
    getFile() {
      console.log('get file')
      this.$refs.inputFile.click()
    },
  },
}
</script>
<style scoped>
.fileContent input[type='file']::-webkit-file-upload-button {
  cursor: pointer;
}
.fileContent label {
  cursor: pointer;
}
.fileContent .fileClass {
  display: none;
  cursor: pointer;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
</style>